package com.ruoyi.quartz.task;


import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.snowRemovingUser.domain.TCsvAbnormal;
import com.snowRemovingUser.mapper.TCsvAbnormalMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;

/**
 * 检查服务器hso文件是否上传
 */
@Component("serverMonitorTask")
public class ServerMonitorTask {


    /** log */
    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private TCsvAbnormalMapper tCsvAbnormalMapper;


    @Value("${linux.localInspectFilePath}")
    private String localInspectFilePath;

    @Value("${formalAttire.serverEnabled}")
    private Boolean serverEnabled;

    @Value("${formalAttire.username2}")
    private String username;

    @Value("${formalAttire.password2}")
    private String password;

    @Value("${formalAttire.ip}")
    private String ip;

    @Value("${formalAttire.destinationFilePath}")
    private String destinationFilePath;


    public void serverMonitor(){

        try {

            String InspectFilePath = "/data/sftp"+destinationFilePath+"backup/zip/";

            boolean exists = false;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            //如果serverEnabled为true就连接数据库服务器文件夹
            if (serverEnabled){

                JSch jsch = new JSch();
                Session session = jsch.getSession(username, ip, 22);
                session.setPassword(password);
                session.setConfig("StrictHostKeyChecking", "no");
                session.connect();
                ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
                sftpChannel.connect();
                ChannelSftp channelSftp = (ChannelSftp) sftpChannel;
                channelSftp.cd(InspectFilePath);
                Vector<ChannelSftp.LsEntry> lsEntries = channelSftp.ls(".");

                long start = getStartTime();
                Date startDate = new Date(start);
                long startDateTimestamp = startDate.getTime() / 1000; // 10位时间戳

                long end = getEndTime();
                Date endDate = new Date(end);
                long endDateTimestamp = endDate.getTime() / 1000; // 10位时间戳

                for (ChannelSftp.LsEntry lsEntry : lsEntries) {
                    if (!lsEntry.getAttrs().isDir()) {

                        if (lsEntry.getAttrs().getMTime() >= startDateTimestamp && lsEntry.getAttrs().getMTime() <= endDateTimestamp){

                            exists = true;
                            logger.info("hso文件已经上传成功");
                        }

                        //System.out.println(lsEntry.getFilename()+"-----"+lsEntry.getAttrs().getMTime());
                    }
                }
                channelSftp.disconnect();
                session.disconnect();

            }else {

                File folder = new File(localInspectFilePath);
                //File folder = new File("C:/Users/10261/Desktop/zip");
                long start = getStartTime();
                long end = getEndTime();
                for (File file : folder.listFiles()) {
                    long lastModified = file.lastModified();
                    if (lastModified >= start && lastModified <= end) {
                        System.out.println(file.getName() + " was modified on " + sdf.format(new Date(lastModified)));
                        exists = true;
                        logger.info("hso文件已经上传成功");
                    }
                }

            }

            //hso文件没有上传成功
            if (!exists) {

                Date date = new Date();
                String today = sdf.format(date);

                String y = today.substring(0, 4);
                String m = today.substring(5, 7);
                String d = today.substring(8, 10);
                String h = today.substring(11, 13);
                Integer hInt = Integer.valueOf(h);

                if (hInt >=7 && hInt <= 9 ){
                    h = "01z";
                } else if(hInt >=12 && hInt <= 14){
                    h = "05z";
                } else if (hInt >=16 && hInt <= 18){
                    h = "09z";
                }else if (hInt >=21 && hInt <= 23){
                    h = "14z";
                }else if (hInt >=4 && hInt <= 6){
                    Integer dInt = Integer.valueOf(d);
                    dInt= dInt-1;
                    String s = dInt.toString();
                    d= s;
                    h = "21z";
                }

                String abnormalContent ="hsoIndex"+y+m+d+h+".tar.gz";

                //异常信息保存到数据库
                TCsvAbnormal tCsvAbnormal = new TCsvAbnormal();
                tCsvAbnormal.setAbnormalContent(abnormalContent+"文件没有上传成功请及时将文件上传至/data/sftp/wniHSOIndex文件夹中");
                tCsvAbnormal.setAbnormalTime(date);
                tCsvAbnormal.setStatus(0);
                tCsvAbnormalMapper.insertTCsvAbnormal(tCsvAbnormal);

                logger.info("生成异常事件成功");

                //发送邮箱提醒开发人员尽快解决异常
                // sendEmail(abnormalContent); //账号申请日期没有下来 暂时不开启
                logger.info("邮箱发送成功");

            }

        } catch (Exception e) {
            logger.error("检查服务器失败",e.getMessage());
        }


    }



    private static long getStartTime() {
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String today = sdf.format(now);
        String eventTime = today.substring(11, 13);
        Integer intTime = Integer.parseInt(eventTime);
        Integer intTime1 = intTime-1;
        String s = intTime1.toString();

        String startTime = today.substring(0, 11) + s +":00:00";
        return convertToLong(startTime);
    }

    private static long getEndTime() {
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String today = sdf.format(now);
        String eventTime = today.substring(11, 13);
        Integer intTime = Integer.parseInt(eventTime);
        Integer intTime1 = intTime+1;
        String s = intTime1.toString();

        String endTime = today.substring(0, 11)+ s +":00:00";
        return convertToLong(endTime);
    }

    private static long convertToLong(String datetime) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = sdf.parse(datetime);
            return date.getTime();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }


//    /**
//     * 发送邮件
//     * @param abnormalContent
//     * @throws MessagingException
//     * @throws UnsupportedEncodingException
//     */
//    private void sendEmail(String abnormalContent) throws MessagingException, UnsupportedEncodingException {
//
//        //发邮件
//        //创建复杂的邮件对象
//        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
//        //true能够添加附件
//        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "utf-8");
//        //设置发送人
//        helper.setFrom(new InternetAddress(MimeUtility.encodeText("藏龙信息科技（苏州）有限公司")+"<clxxweatherhdi@163.com>").toString());
//        //邮件主题
//        helper.setSubject("hsoIndex文件接收失败");
//        //邮件内容  true能够解析html标签
//        if (serverEnabled){
//            // 正式服
//            helper.setText("<h3>"+"测试环境"+abnormalContent+"文件接收失败，<a href='http://129.211.188.229:9104/homepage/index'>点击这里</a>去藏龙信息科技管理系统处理异常</h3>",true);
//        }else {
//
//            // 测试服
//            helper.setText("<h3>"+"测试环境"+abnormalContent+"文件接收失败，<a href='http://42.192.119.47:9104/homepage/index'>点击这里</a>去藏龙信息科技管理系统处理异常</h3>",true);
//        }
//        //收件人
//        //helper.setTo("1026178117@qq.com");
//        helper.setTo(new String[]{"152211565@qq.com","575698632@qq.com","1026178117@qq.com","95737282@qq.com"});
//
//        javaMailSender.send(mimeMessage);
//    }













}
